package com.huaqin.common;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.apache.http.util.EncodingUtils;

import com.huaqin.salestracker.SalesTrackerService;

public class NVRAM {
	private static final String FILE = "data/app/backdata/salesTracer.txt";
	private static final String FILE_BACKUP = "data/app/backdata/salesTracer_backup.txt";
//	private static final String FILE = "mnt/sdcard/SalesTracker.txt";
//	private static final String FILE_BACKUP  = "mnt/sdcard/SalesTracker_BackUp.txt";
	
	private static final String RESIGER_HEADR = "Register = ";
    private static final String RESIGER_TIME = "Register Time:";
	
	private static String  RandomAccessFileRead(String fileName) throws IOException{
		
		RandomAccessFile file = new RandomAccessFile(fileName, "r");
		
		int length = (int)file.length();

        byte [] buffer = new byte[length]; 
         
        file.readFully(buffer);
        
        file.close();
        
        return EncodingUtils.getString(buffer, "UTF-8"); 
		
	}
	
	public static void RandomAccessFileWrite(String  fileName, String write_str) throws IOException{
		
		String temp = "";

		RandomAccessFile file = new RandomAccessFile(fileName, "rw");
		
        if(new File(fileName).exists()){
        	file.seek(file.length());
        	temp = "\n";
        }
        
        file.writeBytes(new SimpleDateFormat("yyyy.MM.dd HH:mm:ss", Locale.getDefault()).format(new Date()) + ":" + write_str + temp);
        
        file.close();
	}
	
	public static void Reset(){
		File file = new File(FILE);
		if(file.exists()){
			file.delete();
        }
	}
	
	public static void Register() {
		RandomAccessFile fileDest = null;
		File file = new File(FILE);
		try{
	        if(file.exists()){
	        	fileDest = new RandomAccessFile(FILE_BACKUP, "rw");
	        	fileDest.writeBytes(RESIGER_HEADR + "true\n");
	        	fileDest.writeBytes(RESIGER_TIME + new SimpleDateFormat("yyyy.MM.dd HH:mm:ss", Locale.getDefault()).format(new Date()) + "\n");
	
	        	RandomAccessFile fileSrc = new RandomAccessFile(FILE, "rw");    
	        	int len = (int)file.length();
	        	byte[] b = new byte[len];    
	        	fileSrc.readFully(b);    
	        	fileDest.write(b);
	
	        	if(file.delete()){
	        		File dest = new File(FILE_BACKUP);
	        		dest.renameTo(new File(FILE));
	        		dest.setReadOnly();
	        	}
	
	        	fileDest.close();
	        	fileSrc.close();
	        }
	        else{
	        	RandomAccessFile destfile = new RandomAccessFile(FILE, "rw");
	        	destfile.writeBytes(RESIGER_HEADR + "true\n");
	        	destfile.writeBytes(RESIGER_TIME + new SimpleDateFormat("yyyy.MM.dd HH:mm:ss", Locale.getDefault()).format(new Date()));
	        	destfile.close();
	        }
		}
		catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	public static boolean isRegister(){
		
        if(!new File(FILE).exists()){
        	return false;
        }

        RandomAccessFile file = null;
        String str = null;
        
		try {
			file = new RandomAccessFile(FILE, "r");

			str = file.readLine();
			
			file.close();

			if(str == null || str.equals("")){
				return false;
			}
		}
		catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (Exception e) {
			// TODO: handle exception
		}
		finally{
		    try {
		        if(file != null){
		            file.close();
		        }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
		}

		return str.substring(RESIGER_HEADR.length()).equals("true");
	}
	
	public static String getRegisterTime(){
        RandomAccessFile file = null;
        String time = null;

	    try {
	        file = new RandomAccessFile(FILE, "r");
	        
	        long len = file.length();
	        String str = null;
	        
	        if (len > 3) {
	            long pos = 0;
	            
	            while(pos < len){
	                ++pos;
	                file.seek(pos);
	                
	                if (file.readByte() == '\n') {
	                    str = file.readLine();
	                    
	                    if(str.startsWith(RESIGER_TIME)){
	                        time = str.substring(RESIGER_TIME.length());
	                        break;
	                    }
	                 }
	            }
	        }
        } catch (Exception e) {
            // TODO: handle exception
        }
	    finally{
           try {
                if(file != null){
                    file.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
	    }
	    
	    return time;
	}
	
	public static void addRecordLog(String log){

		try {
			RandomAccessFileWrite(FILE, log);
		}
		catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static boolean isXmlFileExist(){
		return new File(SalesTrackerService.XMLFILEPATH).exists();
	}
}
